package com.hongyi.web.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.protobuf.ServiceException;
import com.hongyi.result.Result;
import com.hongyi.web.constenum.SysEnum;
import com.hongyi.web.dto.SysDeptDto;
import com.hongyi.web.mapper.SysDeptMapper;
import com.hongyi.web.pojo.SysDept;
import com.hongyi.web.query.SysDeptQueryDto;
import com.hongyi.web.service.ISysDeptService;
import com.hongyi.web.utils.PageResult;
import com.hongyi.web.utils.StringUtils;
import com.hongyi.web.vo.SysDeptVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService
{
    @Autowired
    private SysDeptMapper deptMapper;



    @Override
    public List<SysDeptVo> selectDeptTreeList() {
        List<SysDept> deptsList = deptMapper.selectDeptList();
        List<SysDeptVo> deptsVoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(deptsList)) {
            for (SysDept dept : deptsList) {
                SysDeptVo deptVo = new SysDeptVo();
                BeanUtils.copyProperties(dept, deptVo);
                deptsVoList.add(deptVo);
            }
        }
        return buildDeptTree(deptsVoList);
    }

    @Override
    public PageResult<SysDeptVo> selectPage(SysDeptQueryDto sysDeptQueryDto, Integer pageNum, Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
//        List<SysDeptVo> list = selectDeptTreeList(); // 查询部门列表
        List<SysDept> list = deptMapper.selectDeptQueryList(sysDeptQueryDto);
        List<SysDeptVo> deptsVoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(list)) {
            for (SysDept dept : list) {
                SysDeptVo deptVo = new SysDeptVo();
                BeanUtils.copyProperties(dept, deptVo);
                deptsVoList.add(deptVo);
            }
        }
        List<SysDeptVo> BuildedeptsVoList = buildDeptTree(deptsVoList); // 构建树结构
        PageInfo<SysDeptVo> pageResult = new PageInfo<>(BuildedeptsVoList);
        return new PageResult<>(pageResult.getTotal(), pageResult.getList());
    }

    @Override
    public void deleteDeptById(Long deptId) {
            deptMapper.deleteDeptById(deptId);
    }

    @Override
    public void updateDept(SysDeptDto sysDeptDto) {
        deptMapper.updateDept(sysDeptDto);
    }

    @Override
    public void insertDept(SysDeptDto sysDeptDto)  {
          // 祖序列号
        // 上一次的父级ID
        String ancestors = deptMapper.selectDeptById(sysDeptDto.getParentId()).getAncestors();
        sysDeptDto.setAncestors(ancestors + "," + sysDeptDto.getParentId());
        // 如果父节点不为正常状态，则不允许新增子节点
        if(!deptMapper.selectDeptById(sysDeptDto.getParentId()).getStatus().equals(SysEnum.DEPT_STAUS_ACTIVE.getCode())) {
//            return Result.error("部门停用，不允许新增");
          throw new RuntimeException("部门停用，不允许新增");
        }
        deptMapper.insertDept(sysDeptDto);
    }

    @Override
    public SysDeptVo selectDeptById(Long deptId) {
        SysDeptVo sysDeptVo = new SysDeptVo();
        SysDept  dept =  deptMapper.selectDeptById1(deptId);
        BeanUtils.copyProperties(dept, sysDeptVo);
        return sysDeptVo;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDeptVo> buildDeptTree(List<SysDeptVo> depts)
    {
        List<SysDeptVo> returnList = new ArrayList();
        List<Long> tempList = depts.stream().map(SysDeptVo::getDeptId).collect(Collectors.toList());
        for (SysDeptVo dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);  // 递归
                returnList.add(dept); // 添加到返回列表
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDeptVo> list, SysDeptVo t)
    {
        // 得到子节点列表
        List<SysDeptVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDeptVo tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild); // 递归
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDeptVo> list, SysDeptVo t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<SysDeptVo> getChildList(List<SysDeptVo> list, SysDeptVo t)
    {
        List<SysDeptVo> tlist = new ArrayList();
        Iterator<SysDeptVo> it = list.iterator();
        while (it.hasNext())
        {
            SysDeptVo n = (SysDeptVo) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
